#include <stdio.h>
#include "mem.h"
#include "redobject.h"
#include "redintobject.h"
#include "redfileobject.h"
#include "rednullobject.h"
#include "redtupleobject.h"
#include "redstringobject.h"
#include "redexceptionobject.h"

static RedObject *build_argv(void)
{
	RedObject *argv = RedTuple_FromLength(Red_Argc);

	for (int i = 0; i < Red_Argc; i++)
		RedTuple_Items(argv)[i] = RedString_FromCFormat("%s", Red_Argv[i]);

	return argv;
}

static RedObject *memory_limit(void)
{
	return RedInt_FromInt(RedMem_MaxMemory);
}

static RedObject *set_memory_limit(RedObject *value)
{
	if (!RedInt_Exact(value))
	{
		RedException_ThrowFormat(&RedExc_TypeError, "Memory limit must be an integer");
		return NULL;
	}

	RedMem_MaxMemory = RedInt_Value(value);
	Red_Return_Null();
}

RED_EXPORT char module_entry(RedObject *self, RedObject *name)
{
	if (!RedObject_AddObject(self, "argv"	, build_argv()))						return 0;
	if (!RedObject_AddObject(self, "stdin"	, RedFile_Wrap("<stdin>", stdin)))		return 0;
	if (!RedObject_AddObject(self, "stderr"	, RedFile_Wrap("<stderr>", stderr)))	return 0;
	if (!RedObject_AddObject(self, "stdout"	, RedFile_Wrap("<stdout>", stdout)))	return 0;

	if (!RedObject_AddUnary(self	, "set_memory_limit", set_memory_limit))	return 0;
	if (!RedObject_AddNullary(self	, "memory_limit"	, memory_limit))		return 0;
	return 1;
}
